<template>
	<view class="analysis-container">
		<view class="analysis-header">
			<text class="page-title">数据分析</text>
		</view>
		
		<!-- 数据分析卡片列表 -->
		<view class="analysis-card-list">
			<!-- 销售排行分析 -->
			<view class="analysis-card" @click="navigateTo('/pages/data-analysis/sales-ranking/sales-ranking')">
				<view class="card-title">
					<text class="title-text">销售排行</text>
					<text class="iconfont icon-right"></text>
				</view>
				<view class="card-content">
					<view class="chart-placeholder">
						<!-- 简单预览图表 -->
						<canvas canvas-id="salesCanvas" id="salesCanvas" class="charts"></canvas>
					</view>
				</view>
			</view>
			
			<!-- 评分分布分析 -->
			<view class="analysis-card" @click="navigateTo('/pages/data-analysis/rating-distribution/rating-distribution')">
				<view class="card-title">
					<text class="title-text">评分分布</text>
					<text class="iconfont icon-right"></text>
				</view>
				<view class="card-content">
					<view class="chart-placeholder">
						<!-- 简单预览图表 -->
						<canvas canvas-id="ratingCanvas" id="ratingCanvas" class="charts"></canvas>
					</view>
				</view>
			</view>
			
			<!-- 热门关键词分析 -->
			<view class="analysis-card" @click="navigateTo('/pages/data-analysis/hot-keywords/hot-keywords')">
				<view class="card-title">
					<text class="title-text">热门关键词</text>
					<text class="iconfont icon-right"></text>
				</view>
				<view class="card-content">
					<view class="keyword-cloud">
						<view class="keyword-item" v-for="(item, index) in hotKeywords" :key="index" 
							:style="{ fontSize: item.weight + 'rpx', color: getRandomColor() }">
							{{item.name}}
						</view>
					</view>
				</view>
			</view>
			
			<!-- 市场趋势分析 -->
			<view class="analysis-card" @click="navigateTo('/pages/data-analysis/market-trend/market-trend')">
				<view class="card-title">
					<text class="title-text">市场趋势</text>
					<text class="iconfont icon-right"></text>
				</view>
				<view class="card-content">
					<view class="chart-placeholder">
						<!-- 简单预览图表 -->
						<canvas canvas-id="trendCanvas" id="trendCanvas" class="charts"></canvas>
					</view>
				</view>
			</view>
			
			<!-- 个性化图书推荐 -->
			<view class="analysis-card">
				<view class="card-title">
					<text class="title-text">个性化图书推荐</text>
					<text class="iconfont icon-right" @click="navigateTo('/pages/recommendation/recommendation')"></text>
				</view>
				<view class="card-content">
					<scroll-view scroll-x class="book-scroll">
						<view 
							class="book-card" 
							v-for="(book, index) in personalRecommendations" 
							:key="'personal-'+index"
							@click="goToBookDetail(book.id)"
						>
							<image class="book-cover" :src="book.coverUrl" mode="aspectFill"></image>
							<text class="book-title">{{book.title}}</text>
							<view class="book-rating">
								<uni-rate :value="book.avgRating" size="14" :readonly="true" :is-fill="false"></uni-rate>
								<text class="rating-text">{{book.avgRating || 0}}</text>
							</view>
						</view>
						<view class="empty-tip" v-if="personalRecommendations.length === 0">
							<text>暂无推荐图书</text>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { ref, onMounted } from 'vue';
	import api from '@/api/index.js';
	// 引入正确的图表组件
import uCharts from '@/components/qiun-data-charts/u-charts.js';
	// 引入用户状态管理
	import { useUserStore } from '@/store/user.js';
	
	export default {
		setup() {
			// 图表数据
			const salesChartData = ref(null);
			const ratingChartData = ref(null);
			const trendChartData = ref(null);
			const hotKeywords = ref([]);
			// 个性化推荐图书
			const personalRecommendations = ref([]);
			// 用户状态
			const userStore = useUserStore();
			
			// 颜色池
			const colors = [
				'#1890FF', '#2FC25B', '#FACC14', '#F04864', '#8543E0',
				'#90ED7D', '#F7A35C', '#8085E9', '#F15C80', '#E4D354'
			];
			
			// 初始化
			onMounted(() => {
				loadAnalysisData();
			});
			
			// 加载分析数据
			async function loadAnalysisData() {
				try {
					await Promise.all([
						loadSalesRanking(),
						loadRatingDistribution(),
						loadHotKeywords(),
						loadMarketTrend(),
						loadPersonalRecommendations()
					]);
				} catch (error) {
					console.error('加载分析数据失败:', error);
				}
			}
			
			// 加载个性化推荐
			async function loadPersonalRecommendations() {
				try {
					if (!userStore.currentUser) {
						// 未登录时加载热门图书
						const res = await api.recommendation.getHotBooks({ page: 1, size: 10 });
						if (res && res.data && res.data.list) {
							personalRecommendations.value = res.data.list;
						}
					} else {
						// 已登录时加载个性化推荐
						const userId = userStore.currentUser.id;
						const res = await api.recommendation.getPersonalRecommendations(userId, { page: 1, size: 10 });
						if (res && res.data && res.data.list) {
							personalRecommendations.value = res.data.list;
						} else {
							// 如果个性化推荐失败，则加载热门图书
							const hotRes = await api.recommendation.getHotBooks({ page: 1, size: 10 });
							if (hotRes && hotRes.data && hotRes.data.list) {
								personalRecommendations.value = hotRes.data.list;
							}
						}
					}
				} catch (error) {
					console.error('加载个性化推荐失败:', error);
					// 出错时设置为空数组
					personalRecommendations.value = [];
				}
			}
			
			// 加载销售排行
			async function loadSalesRanking() {
				try {
					const res = await api.analysis.getSalesRanking();
					// 处理API响应 - 确保处理正确的数据结构
					const salesData = (res && res.data && Array.isArray(res.data)) ? res.data : 
					              (res && res.data && res.data.data && Array.isArray(res.data.data)) ? res.data.data : 
					              [];
					              
					// 从数据中提取前5个图书的标题和销量
					const books = salesData.slice(0, 5).map(book => ({
						name: book.title || '未知书名',
						value: book.sales || 0
					}));
					
					const chartData = {
						categories: books.map(item => item.name),
						series: [{
							name: '销售量',
							data: books.map(item => item.value)
						}]
					};
					
					salesChartData.value = chartData;
					
					// 使用简单的方式绘制柱状图
					setTimeout(() => {
						const ctx = uni.createCanvasContext('salesCanvas');
						
						// 清空画布
						ctx.clearRect(0, 0, 300, 200);
						ctx.setFillStyle('#FFFFFF');
						ctx.fillRect(0, 0, 300, 200);
						
						// 绘制标题
						ctx.setFontSize(14);
						ctx.setFillStyle('#333333');
						ctx.fillText('销售排行', 10, 20);
						
						// 简单绘制柱状图
						const data = chartData.series[0].data;
						const labels = chartData.categories;
						const maxValue = Math.max(...data) || 1;
						const barWidth = 30;
						const marginLeft = 40;
						const marginBottom = 30;
						const chartHeight = 150;
						
						// 绘制每个柱子
						data.forEach((value, index) => {
							const barHeight = (value / maxValue) * chartHeight;
							const x = marginLeft + index * (barWidth + 20);
							const y = 200 - marginBottom - barHeight;
							
							// 绘制柱子
							ctx.setFillStyle('#1890FF');
							ctx.fillRect(x, y, barWidth, barHeight);
							
							// 绘制标签
							ctx.setFontSize(10);
							ctx.setFillStyle('#666666');
							ctx.fillText(labels[index], x, 185);
							
							// 绘制数值
							ctx.fillText(value, x + 10, y - 5);
						});
						
						ctx.draw();
					}, 500);
				} catch (error) {
					console.error('加载销售排行失败:', error);
				}
			}
			
			// 加载评分分布
			async function loadRatingDistribution() {
				try {
					const res = await api.analysis.getRatingDistribution();
					
					// 处理API响应 - 确保处理正确的数据结构
					const ratingData = (res && res.data && Array.isArray(res.data)) ? res.data : 
					                (res && res.data && res.data.data && Array.isArray(res.data.data)) ? res.data.data :
					                // 如果前两种情况都不匹配，生成默认数据
					                [
					                  { rating: 5, count: 120 },
					                  { rating: 4, count: 80 },
					                  { rating: 3, count: 40 },
					                  { rating: 2, count: 20 },
					                  { rating: 1, count: 10 }
					                ];
					              
					const chartData = {
						categories: ratingData.map(item => item.rating + '星'),
						series: [{
							name: '评分分布',
							data: ratingData.map(item => item.count)
						}]
					};
					
					ratingChartData.value = chartData;
					
					// 使用简单的方式绘制饼图
					setTimeout(() => {
						const ctx = uni.createCanvasContext('ratingCanvas');
						const data = chartData.series[0].data;
						const labels = chartData.categories;
						
						// 清空画布
						ctx.clearRect(0, 0, 300, 200);
						ctx.setFillStyle('#FFFFFF');
						ctx.fillRect(0, 0, 300, 200);
						
						// 绘制标题
						ctx.setFontSize(14);
						ctx.setFillStyle('#333333');
						ctx.fillText('评分分布', 10, 20);
						
						// 绘制简单饼图
						const centerX = 150;
						const centerY = 100;
						const radius = 60;
						const total = data.reduce((sum, val) => sum + val, 0);
						
						// 饼图颜色
						const colors = ['#1890FF', '#2FC25B', '#FACC14', '#F04864', '#8543E0'];
						
						// 绘制饼图切片
						let startAngle = 0;
						data.forEach((value, index) => {
							const sliceAngle = (value / total) * 2 * Math.PI;
							const endAngle = startAngle + sliceAngle;
							
							// 绘制扇形
							ctx.beginPath();
							ctx.moveTo(centerX, centerY);
							ctx.arc(centerX, centerY, radius, startAngle, endAngle);
							ctx.closePath();
							ctx.setFillStyle(colors[index % colors.length]);
							ctx.fill();
							
							// 计算文本位置，在切片中间
							const midAngle = startAngle + sliceAngle / 2;
							const labelX = centerX + (radius * 0.6) * Math.cos(midAngle);
							const labelY = centerY + (radius * 0.6) * Math.sin(midAngle);
							
							// 绘制标签
							ctx.setFontSize(10);
							ctx.setFillStyle('#FFFFFF');
							ctx.fillText(value, labelX - 6, labelY + 4);
							
							// 为下一个切片更新起始角度
							startAngle = endAngle;
						});
						
						// 绘制图例
						const legendX = 210;
						const legendY = 60;
						
						labels.forEach((label, index) => {
							const y = legendY + index * 20;
							
							// 图例点
							ctx.setFillStyle(colors[index % colors.length]);
							ctx.fillRect(legendX, y - 8, 10, 10);
							
							// 图例文本
							ctx.setFontSize(10);
							ctx.setFillStyle('#666666');
							ctx.fillText(label, legendX + 15, y);
						});
						
						ctx.draw();
					}, 500);
				} catch (error) {
					console.error('加载评分分布失败:', error);
				}
			}
			
			// 加载热门关键词
			async function loadHotKeywords() {
				try {
					const res = await api.analysis.getHotKeywords();
					
					// 处理API响应 - 确保处理正确的数据结构
					const keywordsData = (res && res.data && Array.isArray(res.data)) ? res.data : 
					                  (res && res.data && res.data.data && Array.isArray(res.data.data)) ? res.data.data : 
					                  // 默认热门关键词
					                  [
					                    { keyword: '历史', weight: 1.0 },
					                    { keyword: '科幻', weight: 0.95 },
					                    { keyword: '爱情', weight: 0.85 },
					                    { keyword: '理财', weight: 0.8 },
					                    { keyword: '心理学', weight: 0.75 },
					                    { keyword: '哲学', weight: 0.7 },
					                    { keyword: '自我提升', weight: 0.65 },
					                    { keyword: '道德修养', weight: 0.6 },
					                    { keyword: '时间管理', weight: 0.55 },
					                    { keyword: '人文社科', weight: 0.5 }
					                  ];
					
					// 根据权重设置字体大小，最小24rpx，最大48rpx
					hotKeywords.value = keywordsData.map(item => ({
						name: item.keyword,
						weight: 24 + Math.floor((item.weight || 0.5) * 24)
					})).slice(0, 10);
				} catch (error) {
					console.error('加载热门关键词失败:', error);
				}
			}
			
			// 加载市场趋势
			async function loadMarketTrend() {
				try {
					const res = await api.analysis.getMarketTrend();
					
					// 处理API响应 - 确保处理正确的数据结构
					const trendData = (res && res.data && Array.isArray(res.data)) ? res.data : 
					              (res && res.data && res.data.data && Array.isArray(res.data.data)) ? res.data.data : 
					              // 如果前两种情况都不匹配，生成默认数据
					              [
					                { month: '1月', sales: 80000 },
					                { month: '2月', sales: 65000 },
					                { month: '3月', sales: 90000 },
					                { month: '4月', sales: 110000 },
					                { month: '5月', sales: 95000 },
					                { month: '6月', sales: 120000 },
					              ];
					              
					const chartData = {
						categories: trendData.map(item => item.month),
						series: [{
							name: '销售额',
							data: trendData.map(item => item.sales)
						}]
					};
					
					trendChartData.value = chartData;
					
					// 使用简单的方式绘制折线图
					setTimeout(() => {
						const ctx = uni.createCanvasContext('trendCanvas');
						
						// 清空画布
						ctx.clearRect(0, 0, 300, 200);
						ctx.setFillStyle('#FFFFFF');
						ctx.fillRect(0, 0, 300, 200);
						
						// 绘制标题
						ctx.setFontSize(14);
						ctx.setFillStyle('#333333');
						ctx.fillText('市场趋势', 10, 20);
						
						// 绘制简单折线图
						const marginLeft = 30;
						const marginBottom = 30;
						const marginTop = 40;
						const chartWidth = 250;
						const chartHeight = 130;
						
						const categories = chartData.categories;
						const seriesData = chartData.series;
						
						// 找出所有数据中的最大值
						let maxValue = 0;
						seriesData.forEach(series => {
							const seriesMax = Math.max(...series.data);
							maxValue = Math.max(maxValue, seriesMax);
						});
						maxValue = maxValue || 1; // 防止零分母
						
						// 绘制Y轴
						ctx.beginPath();
						ctx.setLineWidth(1);
						ctx.setStrokeStyle('#CCCCCC');
						ctx.moveTo(marginLeft, marginTop);
						ctx.lineTo(marginLeft, 200 - marginBottom);
						ctx.stroke();
						
						// 绘制X轴
						ctx.beginPath();
						ctx.moveTo(marginLeft, 200 - marginBottom);
						ctx.lineTo(marginLeft + chartWidth, 200 - marginBottom);
						ctx.stroke();
						
						// X轴刻度
						const stepX = chartWidth / (categories.length - 1);
						categories.forEach((category, index) => {
							const x = marginLeft + index * stepX;
							
							ctx.setFontSize(8);
							ctx.setFillStyle('#666666');
							ctx.fillText(category, x - 10, 200 - marginBottom + 15);
						});
						
						// 绘制每个数据系列
						const colors = ['#1890FF', '#2FC25B', '#FACC14', '#F04864'];
						
						seriesData.forEach((series, seriesIndex) => {
							const color = colors[seriesIndex % colors.length];
							const data = series.data;
							
							// 绘制折线
							ctx.beginPath();
							ctx.setLineWidth(2);
							ctx.setStrokeStyle(color);
							
							data.forEach((value, index) => {
								const x = marginLeft + index * stepX;
								const y = 200 - marginBottom - (value / maxValue) * chartHeight;
								
								if (index === 0) {
									ctx.moveTo(x, y);
								} else {
									ctx.lineTo(x, y);
								}
								
								// 绘制数据点
								ctx.setFillStyle(color);
								ctx.beginPath();
								ctx.arc(x, y, 3, 0, Math.PI * 2);
								ctx.fill();
							});
							
							ctx.stroke();
							
							// 绘制图例
							ctx.setFontSize(10);
							ctx.setFillStyle('#666666');
							ctx.fillText(series.name, marginLeft + chartWidth - 50, marginTop + 15 * seriesIndex);
							ctx.setFillStyle(color);
							ctx.fillRect(marginLeft + chartWidth - 70, marginTop - 5 + 15 * seriesIndex, 15, 3);
						});
						
						ctx.draw();
					}, 500);
				} catch (error) {
					console.error('加载市场趋势失败:', error);
				}
			}
			
			// 获取随机颜色
			function getRandomColor() {
				const index = Math.floor(Math.random() * colors.length);
				return colors[index];
			}
			
			// 页面导航
			function navigateTo(url) {
				uni.navigateTo({ url });
			}
			
			// 跳转到图书详情页
			function goToBookDetail(bookId) {
				uni.navigateTo({
					url: `/pages/book-detail/book-detail?id=${bookId}`
				});
			}
			
			return {
				salesChartData,
				ratingChartData,
				trendChartData,
				hotKeywords,
				personalRecommendations,
				getRandomColor,
				navigateTo,
				goToBookDetail
			}
		}
	}
</script>

<style lang="scss">
	.analysis-container {
		padding: 20rpx;
		background-color: #f8f8f8;
		min-height: 100vh;
		
		/* 页面标题 */
		.page-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			padding: 20rpx 0;
		}
		
		/* 分析卡片列表 */
		.analysis-card-list {
			display: flex;
			flex-direction: column;
			gap: 20rpx;
			
			/* 分析卡片 */
			.analysis-card {
				background-color: #fff;
				border-radius: 12rpx;
				box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
				overflow: hidden;
				
				/* 卡片标题 */
				.card-title {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 20rpx;
					border-bottom: 1px solid #f0f0f0;
					
					.title-text {
						font-size: 32rpx;
						font-weight: bold;
						color: #333;
					}
					
					.iconfont {
						color: #ccc;
						font-size: 32rpx;
					}
				}
				
				/* 卡片内容 */
				.card-content {
					padding: 20rpx;
					
					/* 图表占位符 */
					.chart-placeholder {
						height: 300rpx;
						display: flex;
						justify-content: center;
						align-items: center;
						
						/* 图表样式 */
						.charts {
							width: 100%;
							height: 100%;
						}
					}
					
					/* 关键词云 */
					.keyword-cloud {
						display: flex;
						flex-wrap: wrap;
						justify-content: center;
						gap: 16rpx;
						padding: 16rpx;
						
						.keyword-item {
							padding: 6rpx 16rpx;
						}
					}
					
					/* 图书水平滚动区域 */
					.book-scroll {
						width: 100%;
						white-space: nowrap;
						padding: 10rpx 0;
						
						/* 图书卡片样式 */
						.book-card {
							display: inline-block;
							width: 200rpx;
							margin-right: 20rpx;
							vertical-align: top;
							
							/* 图书封面图片 */
							.book-cover {
								width: 200rpx;
								height: 280rpx;
								border-radius: 8rpx;
								background-color: #f0f0f0;
								box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.1);
							}
							
							/* 图书标题 */
							.book-title {
								font-size: 28rpx;
								color: #333;
								line-height: 36rpx;
								height: 72rpx;
								margin-top: 10rpx;
								overflow: hidden;
								text-overflow: ellipsis;
								display: -webkit-box;
								-webkit-line-clamp: 2;
								-webkit-box-orient: vertical;
								white-space: normal;
							}
							
							/* 图书评分 */
							.book-rating {
								display: flex;
								align-items: center;
								margin-top: 6rpx;
								
								/* 评分文本 */
								.rating-text {
									font-size: 24rpx;
									color: #f0ad4e;
									margin-left: 6rpx;
								}
							}
						}
						
						/* 空提示样式 */
						.empty-tip {
							width: 100%;
							height: 200rpx;
							display: flex;
							justify-content: center;
							align-items: center;
							
							text {
								color: #999;
								font-size: 28rpx;
							}
						}
					}
				}
			}
		}
	}
</style>
